/*
 * loadgraph.cpp
 *
 *  Created on: Jun 6, 2011
 *      Author: timothy
 */

#include "loadgraph.h"

#include "debug.h"

#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <string.h>

extern arg_vars *g_ArgVars;

// Opens a file stream, reads the first line for numVertices,
//   and sets an appropriate lineLength.
InFile::InFile()
{
	stream = fopen(g_ArgVars->infile_n, "r");
	tokBuffers = (char**)calloc(omp_get_max_threads(), sizeof(char*));
	lineLength = 250;
	char buf[250];
	ReadLine(buf);
	char *tok = strtok_r(buf, ",", &tokBuffers[omp_get_thread_num()]);
	numVertices = atoi(buf);
	tok = strtok_r(NULL, ",", &tokBuffers[omp_get_thread_num()]);
	numEdges = atoi(tok);
	lineLength = numVertices * (log(numVertices) + 1);
	if(lineLength < 250) lineLength = 250;
//	pdprint(PDPRINT_FILEIN, "Stream index = %ld\n", stream);
	g_ShingleContext->numVertices = numVertices;
}

InFile::~InFile()
{
//	pdprint(PDPRINT_FILEIN, "Stream index = %ld\n", stream);
	if(stream)
		fclose(stream);
	free(tokBuffers);
}

// Reads a line from the input stream into the buffer.
//   This method is OMP critical
int InFile::ReadLine(char *buf)
{
	if(EndOfFile()) return 0;
	char *read;
	read = fgets(buf, lineLength, stream);
	return (read != 0);
}

// Returns 0 if the input line cannot produce shingles.
int InFile::Prune(char *line)
{
	char *buf = (char*)malloc(lineLength);
	char *tok;

	strcpy(buf, line);
	unsigned int count = 1;
	tok = strtok_r(buf, ",", &tokBuffers[omp_get_thread_num()]);
	while(tok)
	{
		tok = strtok_r(NULL, ",", &tokBuffers[omp_get_thread_num()]);
		++count;
	}
	free(buf);

	if(count < g_ArgVars->shingle_length)
		return 0;
	else return 1;
}

// Returns 1 if the stream is at end of file, 0 otherwise.
int InFile::EndOfFile()
{
	return feof(stream);
}

